package com.example.graduatetest.view.model;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.widget.Toolbar;
import androidx.lifecycle.MediatorLiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.example.graduatetest.R;
import com.example.graduatetest.bean.Classes;
import com.example.graduatetest.bean.Student;
import com.example.graduatetest.callback.ClassCallBack;
import com.example.graduatetest.callback.StringCallBack;
import com.example.graduatetest.databinding.ActivityAskLeaveBinding;
import com.example.graduatetest.model.ClassModel;
import com.example.graduatetest.model.NoticeModel;

import java.util.List;

public class AskLeaveViewModel extends ViewModel {
    private Activity activity;
    private ActivityAskLeaveBinding binding;
    private String class_number_send;
    private String label;
    private String titleType = "事假";
    private String[] strArray;
    private MutableLiveData<String> class_number;
    private MutableLiveData<String> class_code;
    private MutableLiveData<String> content_reason;
    private EditText edContent;
    private Classes ownClass;
    private Handler handler = new Handler();
    //输入框初始值
    private int num = 0;
    //输入框最大值
    private int mMaxNum=300;

    public void init(Activity activity,ActivityAskLeaveBinding binding,String class_number_send){
        this.activity = activity;
        this.binding = binding;
        this.class_number_send = class_number_send;
        edContent = binding.edContent;
        if(class_number == null) class_number = new MutableLiveData<>();
        if(class_code == null) class_code = new MutableLiveData<>();
        if(content_reason == null) content_reason = new MutableLiveData<>();
        toolbarInit();
        initClick();
        initView();
    }

    //初始化toolbar
    private void toolbarInit(){
        Toolbar toolbar = binding.toolbar15;
        toolbar.setTitle("请假");
        toolbar.setNavigationIcon(R.drawable.ic_arrow_back_black_24dp);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                activity.onBackPressed();
            }
        });
    }
    ///初始化页面
    private void initView(){
        label = "请假";
        if(!class_number_send.equals("NULL")){
            class_number.setValue(class_number_send);
            binding.edClassNumber.setFocusableInTouchMode(false);
        }
        binding.edContent.addTextChangedListener(new TextWatcher() {
            //记录输入的字数
            private CharSequence wordNum;
            private int selectionStart;
            private int selectionEnd;

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //实时记录输入的字数
                wordNum= s;
            }

            @Override
            public void afterTextChanged(Editable s) {
                int number = num + s.length();
                //TextView显示剩余字数
                binding.textTextNumber.setText("" + number+"/300");
                selectionStart=edContent.getSelectionStart();
                selectionEnd = edContent.getSelectionEnd();
                //判断大于最大值
                if (wordNum.length() > mMaxNum) {
                    //删除多余输入的字（不会显示出来）
                    s.delete(selectionStart - 1, selectionEnd);
                    int tempSelection = selectionEnd;
                    edContent.setText(s);
                    edContent.setSelection(tempSelection);//设置光标在最后
                    //吐司最多输入300字
                    Toast.makeText(activity, "最多输入300字", Toast.LENGTH_SHORT).show();
                }
            }
        });
        //设置spinner
        updateUI();
    }

    //更新spinner
    private void updateUI(){
        strArray = new String[]{"事假","病假","其它"};
        ArrayAdapter<String> adapter=new ArrayAdapter<>(activity,android.R.layout.simple_spinner_item, strArray);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        binding.spinner.setAdapter(adapter);
        binding.spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
                TextView tv = (TextView)view;
                // 修改样式属性
                tv.setTextSize(20f);
                tv.setTextColor(Color.parseColor("#FD315D"));
                tv.setGravity(Gravity.START);
                titleType = tv.getText().toString();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // TODO
            }
        });

    }

    private void initClick(){
        binding.submitButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferences preferences = activity.getSharedPreferences("data", Context.MODE_PRIVATE);
                final String number = preferences.getString("number","2017211973");
                final String name = preferences.getString("name", "默认");
                if(class_number.getValue() != null && titleType != null && class_code.getValue() != null && content_reason.getValue() != null){
                    networkWatch(titleType,content_reason.getValue(),name,number,label,class_number.getValue(),class_code.getValue());
                }else{
                    Toast.makeText(activity, "内容填写不完整", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
    //插入记录
    private void networkWatch(final String title, final String content, final String send_name, final String send_number, final String label, final String class_number, final String class_code){
        ClassModel.getOneClass(class_number, new ClassCallBack() {
            @Override
            public void onSuccess(Classes classes) {
                ownClass = classes;
                if (ownClass != null){
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            networkInsert(title,content,send_name,send_number,label,class_number,class_code,ownClass.getTeacher_number());
                        }
                    });
                }else{
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(activity, "课程号错误", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }

            @Override
            public void onFailed() {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(activity, "网络错误", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });

    }
    private void networkInsert(String title, String content, String send_name, String send_number, String label, String class_number, String class_code,String receive_number){
        NoticeModel.setInsertOneNotice(title, content, send_name, send_number,receive_number , label, class_number, class_code,"未处理", new StringCallBack() {
            @Override
            public void onSuccess(final String result) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        if(result.equals("success")){
                            activity.onBackPressed();
                            Toast.makeText(activity,"请假成功",Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }

            @Override
            public void onFailed() {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(activity, "插入失败", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });

    }

    public MutableLiveData<String> getClass_number() {
        return class_number;
    }

    public MutableLiveData<String> getClass_code() {
        return class_code;
    }

    public MutableLiveData<String> getContent_reason() {
        return content_reason;
    }

}
